<template>
  <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :visible.sync="dialogPvVisible" title="备件详情">
  <div class="app-container">
    <el-descriptions title="备件详情" direction="vertical" :column="2" border>
      <el-descriptions-item :label="$t('bs.spareparts')">{{temp.name}}</el-descriptions-item>
      <el-descriptions-item :label="$t('bs.process')">{{temp.process}}</el-descriptions-item>
      <el-descriptions-item :label="$t('bs.specification')">{{temp.specification}}</el-descriptions-item>
      <el-descriptions-item :label="$t('bs.spm')">{{temp.spm}}</el-descriptions-item>

      <el-descriptions-item :label="$t('bs.sap_code')">{{temp.sap_code}}</el-descriptions-item>

      <el-descriptions-item :label="$t('bs.min_stock')">{{temp.min_stock}}</el-descriptions-item>

      <el-descriptions-item :label="$t('bs.station')">{{temp.station_name}}</el-descriptions-item>
    </el-descriptions>
  </div>
  </el-dialog>
</template>

<script>
import {fetchList, createData, updateData, delData, fetchOne} from '@/api/common'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import CyTreeSelect from '@/components/CyTreeSelect' // secondary package based on el-pagination

export default {
  name: 'spareDetail',
  components: { CyTreeSelect, Pagination },
  directives: { waves },
  data() {
    return {
      checked: true,
      tablesetvisible: false,

      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      station_list:[],

      queryMap: {},
      showReviewer: false,
      listQuery: {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        where: {

        }
      },
      temp: {
        id: '', name: '', process: '', specification: '', supplier: '', spm: '', sap_code: '', min_stock: '', st_id: '' },
      fileds: {
        name: { filed: 'name', title: '关键备件', is_show: '1' },
        process: { filed: 'process', title: '工艺', is_show: '1' },
        specification: { filed: 'specification', title: '规格', is_show: '1' },
        supplier: { filed: 'supplier', title: '图片', is_show: '1' },
        spm: { filed: 'spm', title: 'SPM', is_show: '1' },
        sap_code: { filed: 'sap_code', title: 'sap编码', is_show: '1' },
        min_stock: { filed: 'min_stock', title: '最小库存', is_show: '1' },
        st_id: { filed: 'st_id', title: '工位', is_show: '1' },
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
       update: this.$t("bs.edit"),
        create: this.$t("bs.add")
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '关键备件名称不能为空', trigger: 'change' }],
      },
      downloadLoading: false

    }
  },
  methods: {
    show(id){
      fetchOne({id:id},'spare_parts').then((res)=>{
        console.log(res)
        this.temp=res.data
        this.dialogPvVisible=true;
      })
    },
    getStationList(){
      this.listLoading = true
      fetchList({  page_no: 1,
        limit: 100,
        sort: 'id',}, 'sl_view_station').then(response => {
        if (response.data && response.data.items) {
          this.station_list = response.data.items
        }
        this.listLoading = false
      })
    },
    handleDeleteAll() {
      if (this.multipleSelection.length == 0) {
        this.$message.error('请选择需要删除的数据')
        return
      }
      this.$confirm('你确定删除这' + this.multipleSelection.length + '条数据么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(this.multipleSelection.map(item=>item.id))
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    checkall(val) {
      let check = '1'
      if (!val) {
        check = '0'
      }
      const keys = Object.keys(this.fileds)
      keys.map((item) => {
        this.fileds[item].is_show = check
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery, 'spare_parts').then(response => {
        if (response.data && response.data.items) {
          this.list = response.data.items
          this.total = response.data.count
        }
        this.listLoading = false
      })
    },
    handleFilterReset() {
      this.listQuery = {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        where: {}
      }
      this.getList()
    },
    handleFilter() {
      const ext_keys = ['limit', 'where', 'page_no', 'sort']
      this.listQuery.page_no = 1
      const queryParma = {}
      const listkeys = Object.keys(this.listQuery)

      for (const i in listkeys) {
        if (ext_keys.indexOf(listkeys[i]) == -1 && this.listQuery[listkeys[i]]) {
          console.log('查询', listkeys[i], isNaN(listkeys[i]))
          let operator = '='
          let value = this.listQuery[listkeys[i]]
          if (!this.queryMap[listkeys[i]]) {
            if (isNaN(listkeys[i])) {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({ field: listkeys[i], operator: operator, value: value })
          } else {
            if (this.queryMap[listkeys[i]] == 'like') {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({ field: listkeys[i], operator: operator, value: value })
          }
        }
      }
      this.list = []
      this.listQuery['where'] = queryParma
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: '', name: '', dict_key: '', dict_value: '', img: '', px: '' }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = {
            modelname: 'spare_parts',
            add: this.temp
          }
          createData({ data: [data] }, 'spare_parts').then(() => {
            this.listQuery.where = {}
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = {
            modelname: 'spare_parts',
            update: this.temp
          }
          updateData({ data: [data] }, 'spare_parts').then(() => {
            // const index = this.list.findIndex(v => v.id === this.temp.id)
            // this.list.splice(index, 1, this.temp)
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(ids) {
      console.log("执行删除")
      delData({ id: ids.join(',') }, 'spare_parts').then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.list=[];
        this.total=0;
        this.getList()
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style scoped="scoped" type="scss">
.pagination-container {
  padding: 0px;
  padding-bottom: 16px;
}

.hoverbutton {
  width: 70px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  border-radius: 3px;
}

.hoverbutton:hover {
  border: 1px solid #999999;
}

.setcheckbox .el-checkbox {
  margin-bottom: 10px;
}

.searchform .el-form-item {
  margin-bottom: 0px;
  min-width: 268px;
}
</style>

